package cn.omisheep.au.core.filter;

import cn.omisheep.au.annotation.Decrypt;
import cn.omisheep.au.core.AuKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Constructor;

/**
 * @author zhou xin chen  😊
 * 联系方式 qq:1269670415  email:xinchenzhou666@gmail.com
 */
@Slf4j
public class AuRequestParamHandler implements HandlerMethodArgumentResolver {

    private final AuKey auKey;

    public AuRequestParamHandler(AuKey auKey) {
        this.auKey = auKey;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return (parameter.hasParameterAnnotation(Decrypt.class) || parameter.hasMethodAnnotation(Decrypt.class));
    }

    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        if (request != null) {
            Constructor<?> constructor = parameter.getParameterType().getConstructor(String.class);
            String text = request.getParameter(parameter.getParameterName());
            String decrypt = auKey.decrypt(text);
            return constructor.newInstance(decrypt);
        }
        return null;
    }
}

